<template>
  <div class="iframe-container">
    <!-- 加载中 -->
    <div v-if="loading" class="iframe-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>文件加载中...</span>
    </div>
    
    <!-- iframe渲染区域 -->
    <iframe 
      v-show="!loading"
      ref="iframeRef"
      :src="fileUrl" 
      class="iframe-content" 
      @load="handleIframeLoad"
    ></iframe>
  </div>
</template>

<script>
import { ref, onMounted, defineComponent, watch,onUnmounted } from 'vue'
import { Loading } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'IframeViewer',
  
  components: {
    Loading
  },
  
  props: {
    // 文件URL
    fileUrl: {
      type: String,
      required: true
    }
  },
  
  emits: ['rendered'],
  
  setup(props, { emit }) {
    // 状态
    const loading = ref(true)
    const iframeRef = ref(null)
    
    /**
     * 处理iframe加载完成
     */
    const handleIframeLoad = () => {
      // iframe DOM加载完成，但内容可能还在加载
      console.log('iframe DOM loaded')
    }
    
    /**
     * 处理来自iframe的消息
     */
    const handleMessage = (event) => {
      // 验证消息来源
      if (event.data && event.data.type === 'iframe-loaded') {
        console.log('iframe content loaded:', event.data)
        loading.value = false
        
        // 触发渲染完成事件
        emit('rendered', {
          width: event.data.width || 595,
          height: event.data.height || 842,
          numPages: event.data.numPages || 1,
          pdfPageOriginWidth: [{ page: 1, width: event.data.width || 595 }]
        })
      }
    }
    
    // 监听fileUrl变化，重新加载
    watch(() => props.fileUrl, (newUrl) => {
      if (newUrl) {
        loading.value = true
        console.log('Loading new file:', newUrl)
      }
    })
    
    onMounted(() => {
      // 添加消息监听器
      window.addEventListener('message', handleMessage)
      
      // 初始加载
      if (props.fileUrl) {
        loading.value = true
        console.log('Initial loading:', props.fileUrl)
      }
    })
    
    // 组件卸载时清理事件监听器
    onUnmounted(() => {
      window.removeEventListener('message', handleMessage)
    })
    
    return {
      loading,
      iframeRef,
      handleIframeLoad
    }
  }
})
</script>

<style lang="scss" scoped>
.iframe-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden; /* 移除滚动条，由父容器pdf-container负责滚动 */
  background-color: #f5f5f5;
  
  .iframe-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    
    .loading-icon {
      font-size: 24px;
      margin-bottom: 10px;
      animation: rotating 2s linear infinite;
    }
    
    @keyframes rotating {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  }
  
  .iframe-content {
    width: 100%;
    height: 100%;
    border: none;
    background-color: white;
  }
}
</style>